﻿using HandyControl.Controls;
using HandyControl.Data;
using MeasureAbstract.Base;
using MeasureAbstract.IMotionDevice;
using MeasureAbstract.ISignalGenerator;
using MeasureAbstract.ISilentAreaMeasure;
using MeasureAbstract.IVectorNetworkAnalyzer;
using MeasureLibrary.SilentAreaMeasure;
using Modules;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using 紧缩场反射面装调测试系统.Views;

namespace 紧缩场反射面装调测试系统
{
    public static class SystemManage
    {

        //系统配置文件路径
        public static string ConfigFileName = "SystemConfig.cfg";

        //模块目录路径
        public static string ModulesDirectory = "Modules";

        //系统配置
        public static SystemConfig? SystemConfig { get; set; }

        //系统支持的测量类型
        public static ISilentAreaMeasure? Measure { get; set; }

        //设备模块字典
        public static Dictionary<string, IMotionDevice>? MotionDeviceDict;
        public static Dictionary<string, IVectorNetworkAnalyzer>? VectorNetworkAnalyzerDict;
        public static Dictionary<string, ISignalGenerator>? SignalGeneratorDict;


        //保存系统配置
        public static void SaveConfig()
        {
            string json = JsonConvert.SerializeObject(SystemConfig, Formatting.Indented);
            System.IO.File.WriteAllText(ConfigFileName, json);
        }

        //系统初始化
        public static void Init()
        {
            //读取系统配置文件
            try
            {
                string Json = System.IO.File.ReadAllText(ConfigFileName);
                SystemManage.SystemConfig = JsonConvert.DeserializeObject<SystemConfig>(Json);
                if (SystemManage.SystemConfig == null)
                {
                    throw new Exception("Read config file failed!");
                }
            }
            catch (Exception ex)
            {
                //提示配置文件损坏，是否使用默认配置
                //使用，则创建默认配置，并保存
                //不使用则退出
                //MessageBox.Show($"配置文件损坏，是否使用默认配置?\r\n{ex.Message}");
                if (HandyControl.Controls.MessageBox.Show($"配置文件损坏，是否使用默认配置?\r\n{ex.Message}", "提示", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    //新建立配置文件
                    SystemConfig = new SystemConfig();
                    string json = JsonConvert.SerializeObject(SystemConfig, Formatting.Indented);
                    System.IO.File.WriteAllText(ConfigFileName, json);
                }
                else
                {
                    //退出系统
                    System.Environment.Exit(0);
                }
            }

            //检测模块目录,如果不存在则创建
            if (!System.IO.Directory.Exists(ModulesDirectory))
            {
                System.IO.Directory.CreateDirectory(ModulesDirectory);
            }

            //扫描设备模块
            ModulesManage.ScanModules<IMotionDevice>(ModulesDirectory, ref MotionDeviceDict);
            ModulesManage.ScanModules<IVectorNetworkAnalyzer>(ModulesDirectory, ref VectorNetworkAnalyzerDict);
            ModulesManage.ScanModules<ISignalGenerator>(ModulesDirectory, ref SignalGeneratorDict);


            //创建测量,并构建资源
            switch (SystemConfig.Structure)
            {
                case "转台、矢网":
                    Measure = new SilentAreaMeasure_CommonV2();
                    break;
                case "转台、矢网、信号源":
                    Measure = new SilentAreaMeasure_VSM();
                    break;
                default:
                    throw new Exception("未知的测试设备组成\n");
            }

            //根据配置文件保存的数据确定关联哪一个设备对象
            if (!MotionDeviceDict.Keys.Contains(SystemConfig.SelectedMotionDevice))
            {
                //如果没有对应模块，则使用模块列表中的第一个
                if (MotionDeviceDict.Count > 0)
                {
                    Measure.DeviceList[0] = MotionDeviceDict.First().Value;
                    SystemConfig.SelectedMotionDevice = MotionDeviceDict.First().Key;
                    SystemConfig.MotionDeviceConfig = (Measure.DeviceList[0] as IMotionDevice).Config;
                }
                else
                {
                    //未找到可用运动设备模块
                    Growl.Error("未找到可用运动设备模块,系统启动失败!");
                    return;
                }
            }
            else
            {
                Measure.DeviceList[0] = MotionDeviceDict[SystemConfig.SelectedMotionDevice];
            }

            if (!VectorNetworkAnalyzerDict.Keys.Contains(SystemConfig.SelectedVectorNetworkAnalyzer))
            {
                if (VectorNetworkAnalyzerDict.Count > 0)
                {
                    Measure.DeviceList[1] = VectorNetworkAnalyzerDict.First().Value;
                    SystemConfig.SelectedVectorNetworkAnalyzer = VectorNetworkAnalyzerDict.First().Key;
                    SystemConfig.VectorNetworkAnalyzerConfig = (Measure.DeviceList[1] as IVectorNetworkAnalyzer).Config;
                }
                else
                {
                    Growl.Error("未找到可用矢量网络分析仪模块,系统启动失败!");
                    return;
                }
            }
            else
            {
                Measure.DeviceList[1] = VectorNetworkAnalyzerDict[SystemConfig.SelectedVectorNetworkAnalyzer];
            }

            //恢复配置
            if (SystemConfig.MotionDeviceConfig != null)
            {
                (Measure.DeviceList[0] as IMotionDevice).Config = SystemConfig.MotionDeviceConfig;
            }
            if (SystemConfig.VectorNetworkAnalyzerConfig != null)
            {
                (Measure.DeviceList[1] as IVectorNetworkAnalyzer).Config = SystemConfig.VectorNetworkAnalyzerConfig;
            }



            //如果是三仪器架构，增加对信号发生器的支持
            if (SystemConfig.Structure == "转台、矢网、信号源")
            {
                if (!SignalGeneratorDict.Keys.Contains(SystemConfig.SelectedSignalGenerator))
                {
                    if (SignalGeneratorDict.Count > 0)
                    {
                        Measure.DeviceList[2] = SignalGeneratorDict.First().Value;
                        SystemConfig.SelectedSignalGenerator = SignalGeneratorDict.First().Key;
                        SystemConfig.SignalGeneratorConfig = (Measure.DeviceList[2] as ISignalGenerator).Config;
                    }
                    else
                    {
                        Growl.Error("未找到可用信号发生器模块,系统启动失败!");
                        return;
                    }
                }
                else
                {
                    Measure.DeviceList[2] = SignalGeneratorDict[SystemConfig.SelectedSignalGenerator];
                }
                if (SystemConfig.SignalGeneratorConfig != null)
                {
                    (Measure.DeviceList[2] as ISignalGenerator).Config = SystemConfig.SignalGeneratorConfig;
                }
            }


            //将测量对象关联到使用页面的ViewModel中,并设置ViewModel中的有关变量
            InstrumentSetup.ViewModel.SelectedMotionDevice = SystemConfig.SelectedMotionDevice;
            InstrumentSetup.ViewModel.MotionDeviceList = new ObservableCollection<string>(MotionDeviceDict.Keys);
            InstrumentSetup.ViewModel.SelectedVectorNetworkAnalyzer = SystemConfig.SelectedVectorNetworkAnalyzer;
            InstrumentSetup.ViewModel.VectorNetworkAnalyzerList = new ObservableCollection<string>(VectorNetworkAnalyzerDict.Keys);
            InstrumentSetup.ViewModel.SelectedSignalGenerator = SystemConfig.SelectedSignalGenerator;
            InstrumentSetup.ViewModel.SignalGeneratorList = new ObservableCollection<string>(SignalGeneratorDict.Keys); 
            InstrumentSetup.ViewModel.Measure = Measure;


            DirectionalPatternTest.ViewModel.Measure = Measure;
            DirectionalPatternTest.ViewModel.Measure.SystemConfig = SystemConfig;
            DirectionalPatternTest.ViewModel.Measure.FileType = SystemConfig.DefaultFileFormat;

            
            DataProcess.ViewModel.Measure = Measure;

            SystemSetting.ViewModel.SystemConfig = SystemManage.SystemConfig;

            Measure.SystemConfig = SystemManage.SystemConfig; //将系统配置给测量对象的数据

            //其他
            SaveConfig();

            if (SystemConfig.Structure == "转台、矢网、信号源")
            {
                //如果是3设备架构，则自动打开设备同步
                (Measure.DeviceList[1] as IVectorNetworkAnalyzer).DeviceInteractEnable = true;
            }

            //启动完成
            GrowlInfo Info = new GrowlInfo();
            Info.WaitTime = 0;
            Info.Message = "系统启动完成!";
            //Growl.Success("系统启动完成!");
            Growl.Success(Info);

            if (SystemConfig.DebugMode)
            {
                Growl.Info("已开启调试模式!");
            }
        }
    }
}
